<template>
  <view :data-theme="globPrimary">
    <u-navbar>
      <exam-count-down
        ref="examCountDown"
        :timestamp="timestamp"
        :pattern="pattern"
        :autoplay="false"
        :custom-style="{
          fontSize: '32rpx',
          color: '#303133',
        }"
        @change="handleTimestampChange"
        @end="handleTimestampEnd"
      ></exam-count-down>
      <view class="topic-navbar-sheet" @click="$u.debounce(onOpenCard, 200)">
        <u-image
          width="40"
          height="40"
          src="@/pageFound/static/images/exam_sheet_icon.png"
        ></u-image>
      </view>
      <view class="topic-navbar-btn">
        <edu-button type="primary" size="mini" @click="handleTopicConfirm" :disabled="disabled"
          >交卷</edu-button
        >
      </view>
    </u-navbar>
    <view class="topic-header u-flex u-line-1">
      <view class="title u-line-1">{{ examTitle }}</view>
      <u-image
        width="28rpx"
        height="32rpx"
        src="@/pageFound/static/images/maker.png"
        class="img"
      ></u-image>
      <view class="conut active">{{ examIndex + 1 }}</view>
      <view class="conut">/{{ examCount }}</view>
    </view>

    <view class="topic-body" v-for="item in topicList" :key="item.id">
      <exam-question
        :question="item"
        :question-id="item.id"
        :question-type="item.question_type"
        :value="questionValue(item)"
        :score-item="topicScoreItem"
        @change="handleQuestionChange"
      ></exam-question>
    </view>

    <exam-pagination
      :show-prev-button="examIndex > 0"
      :show-next-button="examIndex < examCount - 1"
      @prev="handleTopicPrev"
      @next="handleTopicNext"
    ></exam-pagination>

    <!-- 答题卡 -->
    <exam-card
      v-model="cardVisible"
      :title="examTitle"
      :timestamp="timestamp"
      :pattern="pattern"
      :disabled="disabled"
      @change="handleTopicChange"
      @confirm="handleTopicConfirm"
    ></exam-card>

    <u-modal
      show-cancel-button
      v-model="modelVisible"
      :show-title="false"
      @confirm="onSubmitPaper"
      content="确认提交试卷吗？"
      :confirm-style="{ 'border-left': '1px solid #e4e7ed' }"
      :confirm-color="globPrimaryColor"
    >
    </u-modal>

    <u-toast ref="uToast" />
  </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import examQuestion from '../components/exam-question.vue'
import examPagination from '../components/exam-pagination.vue'
import examCard from '../components/exam-card.vue'
import examCountDown from '../components/exam-count-down.vue'
import { uploadFile } from '@/utils/uploadFile.js'
export default {
  components: {
    examQuestion,
    examPagination,
    examCard,
    examCountDown,
  },
  data() {
    return {
      paperId: 0,
      paperType: 0, //  类型【1：派发考试；】
      loading: false,
      pattern: false, // 时长规则
      timestamp: 0, // 时长
      examTitle: '', // 考试标题
      examCount: 0, // 试题总数
      examWhen: 0, // 考试用时
      visibleAnswer: 0,
      topicList: [],
      cardVisible: false,
      modelVisible: false,
      uniqueCode: '',
      courseId: 0, // 课程id
      disabled: false,

      cutScreenNumber: 0, // 切屏次数
      cutScreenVerify: 0, // 切屏验证次数

      examShare: 0,
    }
  },
  computed: {
    ...mapState({
      examIndex: (state) => state.examination.examIndex,
      examList: (state) => state.examination.examList,
      examAnswerList: (state) => state.examination.examAnswerList,
      examRulesList: (state) => state.examination.examRulesList,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      topicId: 'examination/getTopicId', // 试题id
    }),
    // 试题的分数
    topicScoreItem() {
      let item = this.examList.find((topic) => topic.topic_id == this.topicId)
      if (item) {
        return item
      }
      return {}
    },
    // 部分id
    partsId() {
      let id = 0
      this.examRulesList.forEach((question) => {
        question.value.forEach((item) => {
          if (item.topic_id == this.topicId) {
            id = question.id
          }
        })
      })
      return id
    },
  },
  onLoad(option) {
    this.paperId = option.id
    if (!this.$u.test.empty(option.course_id)) {
      this.courseId = option.course_id
    }
    if (!this.$u.test.empty(option.type)) {
      this.paperType = option.type
    }
    if (!this.$u.test.empty(option.s)) {
      this.examShare = option.s
    }
    this.getPaperInfo()
  },
  onShow() {
    this.onPageVisibility()
  },
  onHide() {
    // 记录退出到后台次数
    this.cutScreenNumber++
  },
  methods: {
    // 获取的基础信息
    getPaperInfo() {
      this.loading = true
      this.$edu.api
        .getPaperBaser({
          paper_id: this.paperId,
        })
        .then((res) => {
          const { data } = res
          this.examTitle = data.title
          this.examCount = data.total_count
          this.uniqueCode = data.unique_code
          this.visibleAnswer = data.visible_answer
          this.cutScreenVerify = data.screen_cut //切屏次数
          this.$store.commit('examination/init', data.parts)
          this.getExamTopic()
          // 考试时长
          if (data.total_time > 0) {
            this.pattern = true
            this.timestamp = data.total_time * 60
          }
          this.handleTimestampStart()
        })
    },
    // 获取试题
    getExamTopic() {
      uni.showLoading({
        title: '加载中...',
      })
      this.loading = true
      return new Promise((resolve) => {
        this.$edu.api
          .getPaperTopic({
            topic_id: this.topicId,
            paper_id: this.paperId,
          })
          .then((res) => {
            const { data } = res
            this.topicList = data
            setTimeout(() => {
              this.loading = false
              uni.hideLoading()
            }, 500)
            resolve()
          })
          .catch((err) => {
            uni.hideLoading()
          })
      })
    },
    // 当前值
    questionValue(item) {
      let list = this.examAnswerList.reduce((pre, cur) => pre.concat(cur.data), [])
      const rules = list.find((item) => item.topic_id == this.topicId)
      let empty = null
      if (this.$edu.test.inArray(item.question_type, [1, 2, 8])) {
        empty = ''
      } else if (this.$edu.test.inArray(item.question_type, [3, 4, 5, 7])) {
        empty = []
      }

      if (this.$u.test.empty(rules) || this.$u.test.empty(rules.answer)) {
        return empty || ''
      } else {
        return rules.answer
      }
    },
    // 上一题
    handleTopicPrev() {
      if (!this.loading) {
        this.$store.commit('examination/prev')
        this.getExamTopic()
      }
    },
    // 下一题
    handleTopicNext() {
      if (!this.loading) {
        this.$store.commit('examination/next')
        this.getExamTopic()
      }
    },
    // 当前题
    handleTopicChange(index) {
      if (!this.loading) {
        this.cardVisible = false
        this.$store.commit('examination/change', index)
        this.getExamTopic()
      }
    },
    // 选择的答案变化时
    handleQuestionChange(e) {
      this.$store.commit('examination/changeCurrentAnswer', {
        pid: e.pid,
        id: e.id,
        answer: e.answer,
        topic_level: e.topic_level,
        question_type: e.question_type,
        part_id: this.partsId,
      })
    },
    // 打开答题卡
    onOpenCard() {
      this.cardVisible = true
    },
    // 开始计时
    handleTimestampStart() {
      this.$refs.examCountDown.start()
    },
    // 暂停计时
    handleTimestampPause() {
      this.$refs.examCountDown.pause()
    },
    // 时间改变时
    handleTimestampChange(time) {
      this.timestamp = time
      this.examWhen++
    },
    // 时间结束/交卷
    handleTimestampEnd() {
      this.onSubmitPaper()
    },
    // 交卷
    handleTopicConfirm() {
      this.modelVisible = true
    },
    // 处理提交试卷
    onSubmitPaper() {
      this.disabled = true
      this.handleTimestampPause() // 暂停计时
      uni.showLoading()
      let list = this.examAnswerList
      // 处理答案的数据
      let empty = list.every((item) => this.$u.test.empty(item.data))
      if (empty) {
        list = []
      } else {
        list.forEach((question, j) => {
          question.data.forEach((item, index) => {
            if (this.$u.test.empty(item.answer)) {
              question.data.splice(index, 1)
            } else {
              if (this.$edu.test.inArray(item.question_type, [1, 2, 8])) {
                item.answer = [item.answer]
              }
            }
          })
        })

        list.forEach((question, j) => {
          if (this.$u.test.empty(question.data)) {
            list.splice(j, 1)
          }
        })
      }

      setTimeout(() => {
        this.$edu.api
          .referExamAnswer({
            paper_id: parseInt(this.paperId), // 试卷ID
            answer_data: JSON.stringify(list), // 答案数据，json数组，只组装用户作答的题目答案
            unique_code: this.uniqueCode, // 唯一标识
            time_takes: this.examWhen, // 考试用时/秒
            course_id: parseInt(this.courseId) || 0, // 课程考试必传，默认0
            is_assign: this.paperType == 1 ? this.paperType : 0, // 是否为指派考试
          })
          .then((res) => {
            this.$u.toast(res.msg)
            setTimeout(() => {
              uni.hideLoading()
              this.disabled = false
              if (this.visibleAnswer == 1) {
                this.$u.route({
                  type: 'redirectTo',
                  url: '/pageFound/exam/record/index',
                  params: {
                    id: res.data.id,
                  },
                })
              } else {
                this.$u.route({
                  type: 'redirectTo',
                  url: '/pageUser/exam/record',
                })
              }
            }, 300)
          })
          .catch((err) => {
            uni.hideLoading()
            this.$u.route({
              type: 'back',
            })
            this.disabled = false
          })
      }, 1000)
    },
    // 处理切屏
    onPageVisibility() {
      if (this.cutScreenVerify == 0) return
      // 切换次数大于验证次数时自动提交试卷
      if (this.cutScreenNumber > this.cutScreenVerify) {
        this.$refs.uToast.show({
          title: `你已经切换离开考试页面超过${this.cutScreenVerify}次系统将自动提交答卷！`,
          type: 'warning',
          duration: 3000,
        })
        setTimeout(() => {
          // 提交答案
          this.onSubmitPaper()
        }, 3000)
      }
      // 切换次数等于验证次数时提示用户
      if (this.cutScreenNumber == this.cutScreenVerify) {
        this.$refs.uToast.show({
          title: `你已经切换离开考试页面${this.cutScreenNumber}次，如果超过${this.cutScreenVerify}次系统会自动提交答卷，请认真作答！`,
          type: 'warning',
          duration: 5000,
        })
      }
    },
  },
  destroyed() {
    this.$store.commit('examination/init')
  },
}
</script>
<style lang="scss">
page {
  background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.topic-navbar-sheet {
  padding: 10rpx 20rpx;
  margin-left: auto;
  margin-right: 30rpx;
}
.topic-navbar-btn {
  margin-right: 30rpx;
}
.topic-header {
  padding: 30rpx;
  position: relative;
  .title {
    max-width: 60%;
    font-size: 32rpx;
    font-weight: 500;
    color: #303133;
  }
  .img {
    margin-left: auto;
    margin-right: 20rpx;
  }
  .count {
    font-size: 26rpx;
    color: #909399;
  }
  .active {
    @include text-color();
  }
  .answered {
    position: absolute;
    right: 8rpx;
    top: 16rpx;
    z-index: 99;
  }
}
.topic-body {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}
</style>
